import 'package:flutter/material.dart';
import 'package:font_awesome_flutter/font_awesome_flutter.dart';
import 'package:jiyun_behavior/utils/app_theme.dart';
import 'package:jiyun_behavior/widgets/custom_button.dart';

class ScriptureScreen extends StatefulWidget {
  const ScriptureScreen({Key? key}) : super(key: key);

  @override
  State<ScriptureScreen> createState() => _ScriptureScreenState();
}

class _ScriptureScreenState extends State<ScriptureScreen> {
  final GlobalKey _canvasKey = GlobalKey();
  List<DrawingPoint?> _points = [];
  Color _selectedColor = Colors.black;
  double _brushSize = 3.0;
  int _currentPage = 0;
  final List<String> _scriptures = [
    '上善若水，水善利万物而不争，处众人之所恶，故几于道。居善地，心善渊，与善仁，言善信，政善治，事善能，动善时。夫唯不争，故无尤。',
    '道可道，非常道。名可名，非常名。无名天地之始，有名万物之母。故常无欲，以观其妙；常有欲，以观其徼。此两者同出而异名，同谓之玄。玄之又玄，众妙之门。',
    '天下皆知美之为美，斯恶已。皆知善之为善，斯不善已。故有无相生，难易相成，长短相较，高下相倾，音声相和，前后相随。是以圣人处无为之事，行不言之教；万物作焉而不辞，生而不有，为而不恃，功成而弗居。夫唯弗居，是以不去。'
  ];

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: const Text('抄经修行'),
      ),
      body: SafeArea(
        child: SingleChildScrollView(
          child: Padding(
            padding: const EdgeInsets.all(16.0),
            child: Column(
              children: [
                _buildProgressCard(),
                const SizedBox(height: 20),
                _buildRecommendedScriptures(),
                const SizedBox(height: 20),
                _buildScriptureWritingArea(),
                const SizedBox(height: 20),
                _buildScriptureRecords(),
              ],
            ),
          ),
        ),
      ),
    );
  }

  Widget _buildProgressCard() {
    return Card(
      child: Padding(
        padding: const EdgeInsets.all(16.0),
        child: Column(
          children: [
            Row(
              children: [
                Container(
                  width: 60,
                  height: 60,
                  decoration: BoxDecoration(
                    color: AppTheme.secondaryColor,
                    borderRadius: BorderRadius.circular(30),
                  ),
                  child: const Icon(
                    FontAwesomeIcons.book,
                    size: 24,
                    color: AppTheme.primaryColor,
                  ),
                ),
                const SizedBox(width: 16),
                Expanded(
                  child: Column(
                    crossAxisAlignment: CrossAxisAlignment.start,
                    children: [
                      Text(
                        '今日抄经',
                        style: Theme.of(context).textTheme.titleLarge,
                      ),
                      const SizedBox(height: 4),
                      Text(
                        '连续抄经 7 天，当前运势提升 15%',
                        style: TextStyle(
                          fontSize: 14,
                          color: AppTheme.subtitleColor,
                        ),
                      ),
                    ],
                  ),
                ),
              ],
            ),
            const SizedBox(height: 16),
            ClipRounded(
              child: LinearProgressIndicator(
                value: 0.35,
                backgroundColor: const Color(0xFFF5F5F5),
                valueColor: AlwaysStoppedAnimation<Color>(AppTheme.primaryColor),
                minHeight: 8,
              ),
            ),
            const SizedBox(height: 8),
            Row(
              mainAxisAlignment: MainAxisAlignment.spaceBetween,
              children: [
                Text(
                  '今日进度: 35%',
                  style: TextStyle(
                    fontSize: 12,
                    color: AppTheme.lightTextColor,
                  ),
                ),
                Text(
                  '目标: 1 篇/天',
                  style: TextStyle(
                    fontSize: 12,
                    color: AppTheme.lightTextColor,
                  ),
                ),
              ],
            ),
          ],
        ),
      ),
    );
  }

  Widget _buildRecommendedScriptures() {
    return Card(
      child: Padding(
        padding: const EdgeInsets.all(16.0),
        child: Column(
          crossAxisAlignment: CrossAxisAlignment.start,
          children: [
            Text(
              '推荐经书',
              style: Theme.of(context).textTheme.titleLarge,
            ),
            const SizedBox(height: 8),
            Text(
              '根据您的命理基本盘，我们为您推荐以下经书',
              style: TextStyle(
                fontSize: 14,
                color: AppTheme.subtitleColor,
              ),
            ),
            const SizedBox(height: 16),
            SizedBox(
              height: 200,
              child: ListView(
                scrollDirection: Axis.horizontal,
                children: [
                  _buildScriptureItem('太上感应篇', AppTheme.secondaryColor, AppTheme.primaryColor, '提升福报'),
                  const SizedBox(width: 12),
                  _buildScriptureItem('心经', const Color(0xFFE6F7FF), const Color(0xFF1890FF), '化解烦恼'),
                  const SizedBox(width: 12),
                  _buildScriptureItem('道德经', const Color(0xFFF6FFED), const Color(0xFF52C41A), '增长智慧'),
                ],
              ),
            ),
          ],
        ),
      ),
    );
  }

  Widget _buildScriptureItem(String title, Color bgColor, Color iconColor, String description) {
    return Column(
      children: [
        Container(
          width: 120,
          height: 160,
          decoration: BoxDecoration(
            color: bgColor,
            borderRadius: BorderRadius.circular(8),
          ),
          child: Center(
            child: Icon(
              FontAwesomeIcons.bookOpen,
              size: 36,
              color: iconColor,
            ),
          ),
        ),
        const SizedBox(height: 8),
        Text(
          title,
          style: const TextStyle(
            fontSize: 14,
            fontWeight: FontWeight.bold,
          ),
        ),
        Text(
          description,
          style: TextStyle(
            fontSize: 12,
            color: AppTheme.subtitleColor,
          ),
        ),
      ],
    );
  }

  Widget _buildScriptureWritingArea() {
    return Card(
      child: Padding(
        padding: const EdgeInsets.all(16.0),
        child: Column(
          crossAxisAlignment: CrossAxisAlignment.start,
          children: [
            Text(
              '抄经区',
              style: Theme.of(context).textTheme.titleLarge,
            ),
            const SizedBox(height: 16),
            Container(
              padding: const EdgeInsets.all(16),
              decoration: BoxDecoration(
                color: const Color(0xFFF9F9F9),
                borderRadius: BorderRadius.circular(8),
              ),
              child: Column(
                children: [
                  Text(
                    _scriptures[_currentPage],
                    style: const TextStyle(
                      fontSize: 16,
                      height: 1.8,
                    ),
                    textAlign: TextAlign.center,
                  ),
                  const SizedBox(height: 16),
                  Align(
                    alignment: Alignment.centerRight,
                    child: Text(
                      '—— 《道德经》第${_currentPage + 1}章',
                      style: TextStyle(
                        fontSize: 14,
                        color: AppTheme.lightTextColor,
                      ),
                    ),
                  ),
                ],
              ),
            ),
            const SizedBox(height: 16),
            Row(
              mainAxisAlignment: MainAxisAlignment.spaceBetween,
              children: [
                Text(
                  '请使用手指或触控笔在下方区域抄写经文',
                  style: TextStyle(
                    fontSize: 14,
                    color: AppTheme.subtitleColor,
                  ),
                ),
                OutlinedButton(
                  onPressed: _clearCanvas,
                  style: OutlinedButton.styleFrom(
                    padding: const EdgeInsets.symmetric(horizontal: 8, vertical: 4),
                    minimumSize: Size.zero,
                    tapTargetSize: MaterialTapTargetSize.shrinkWrap,
                  ),
                  child: const Text('清除', style: TextStyle(fontSize: 12)),
                ),
              ],
            ),
            const SizedBox(height: 16),
            Container(
              height: 300,
              decoration: BoxDecoration(
                border: Border.all(color: AppTheme.dividerColor),
                borderRadius: BorderRadius.circular(8),
                color: Colors.white,
              ),
              child: Stack(
                children: [
                  // 背景网格
                  CustomPaint(
                    size: const Size(double.infinity, 300),
                    painter: GridPainter(),
                  ),
                  // 手写画布
                  GestureDetector(
                    onPanStart: (details) {
                      setState(() {
                        _points.add(
                          DrawingPoint(
                            details.localPosition,
                            Paint()
                              ..color = _selectedColor
                              ..strokeWidth = _brushSize
                              ..strokeCap = StrokeCap.round,
                          ),
                        );
                      });
                    },
                    onPanUpdate: (details) {
                      setState(() {
                        _points.add(
                          DrawingPoint(
                            details.localPosition,
                            Paint()
                              ..color = _selectedColor
                              ..strokeWidth = _brushSize
                              ..strokeCap = StrokeCap.round,
                          ),
                        );
                      });
                    },
                    onPanEnd: (details) {
                      setState(() {
                        _points.add(null);
                      });
                    },
                    child: CustomPaint(
                      key: _canvasKey,
                      size: const Size(double.infinity, 300),
                      painter: DrawingPainter(_points),
                    ),
                  ),
                ],
              ),
            ),
            const SizedBox(height: 16),
            Row(
              children: [
                Expanded(
                  child: OutlinedButton(
                    onPressed: _currentPage > 0 ? _previousPage : null,
                    child: const Text('上一页'),
                  ),
                ),
                const SizedBox(width: 10),
                Expanded(
                  child: OutlinedButton(
                    onPressed: _currentPage < _scriptures.length - 1 ? _nextPage : null,
                    child: const Text('下一页'),
                  ),
                ),
              ],
            ),
            const SizedBox(height: 16),
            Row(
              mainAxisAlignment: MainAxisAlignment.spaceBetween,
              children: [
                Row(
                  children: [
                    Text(
                      '笔触粗细',
                      style: TextStyle(
                        fontSize: 14,
                        color: AppTheme.subtitleColor,
                      ),
                    ),
                    const SizedBox(width: 10),
                    SizedBox(
                      width: 80,
                      child: Slider(
                        value: _brushSize,
                        min: 1,
                        max: 10,
                        divisions: 9,
                        onChanged: (value) {
                          setState(() {
                            _brushSize = value;
                          });
                        },
                      ),
                    ),
                  ],
                ),
                Row(
                  children: [
                    Text(
                      '墨色',
                      style: TextStyle(
                        fontSize: 14,
                        color: AppTheme.subtitleColor,
                      ),
                    ),
                    const SizedBox(width: 10),
                    _buildColorOption(Colors.black),
                    const SizedBox(width: 5),
                    _buildColorOption(const Color(0xFF333333)),
                    const SizedBox(width: 5),
                    _buildColorOption(const Color(0xFF666666)),
                  ],
                ),
              ],
            ),
            const SizedBox(height: 16),
            Row(
              children: [
                Expanded(
                  child: OutlinedButton(
                    onPressed: () {
                      // 保存草稿逻辑
                    },
                    child: const Text('保存草稿'),
                  ),
                ),
                const SizedBox(width: 10),
                Expanded(
                  child: ElevatedButton(
                    onPressed: () {
                      // 提交抄经逻辑
                      ScaffoldMessenger.of(context).showSnackBar(
                        const SnackBar(
                          content: Text('抄经提交成功，获得5点福报'),
                          backgroundColor: AppTheme.primaryColor,
                        ),
                      );
                      _clearCanvas();
                    },
                    child: const Text('提交抄经'),
                  ),
                ),
              ],
            ),
          ],
        ),
      ),
    );
  }

  Widget _buildColorOption(Color color) {
    return GestureDetector(
      onTap: () {
        setState(() {
          _selectedColor = color;
        });
      },
      child: Container(
        width: 20,
        height: 20,
        decoration: BoxDecoration(
          color: color,
          shape: BoxShape.circle,
          border: Border.all(
            color: _selectedColor == color ? AppTheme.primaryColor : Colors.transparent,
            width: 2,
          ),
        ),
      ),
    );
  }

  Widget _buildScriptureRecords() {
    return Card(
      child: Padding(
        padding: const EdgeInsets.all(16.0),
        child: Column(
          crossAxisAlignment: CrossAxisAlignment.start,
          children: [
            Text(
              '抄经记录',
              style: Theme.of(context).textTheme.titleLarge,
            ),
            const SizedBox(height: 16),
            _buildScriptureRecord('太上感应篇', AppTheme.secondaryColor, '2023-06-10 09:15', 5),
            const Divider(),
            _buildScriptureRecord('心经', const Color(0xFFE6F7FF), '2023-06-09 20:30', 3),
            const Divider(),
            _buildScriptureRecord('道德经', const Color(0xFFF6FFED), '2023-06-08 15:45', 7),
          ],
        ),
      ),
    );
  }

  Widget _buildScriptureRecord(String title, Color bgColor, String time, int points) {
    return Row(
      mainAxisAlignment: MainAxisAlignment.spaceBetween,
      children: [
        Row(
          children: [
            Container(
              width: 40,
              height: 40,
              decoration: BoxDecoration(
                color: bgColor,
                shape: BoxShape.circle,
              ),
              child: const Center(
                child: Icon(
                  FontAwesomeIcons.book,
                  size: 16,
                  color: AppTheme.primaryColor,
                ),
              ),
            ),
            const SizedBox(width: 12),
            Column(
              crossAxisAlignment: CrossAxisAlignment.start,
              children: [
                Text(
                  title,
                  style: const TextStyle(
                    fontSize: 14,
                    fontWeight: FontWeight.bold,
                  ),
                ),
                Text(
                  time,
                  style: TextStyle(
                    fontSize: 12,
                    color: AppTheme.lightTextColor,
                  ),
                ),
              ],
            ),
          ],
        ),
        Text(
          '+$points 福报',
          style: const TextStyle(
            color: AppTheme.primaryColor,
            fontWeight: FontWeight.bold,
          ),
        ),
      ],
    );
  }

  void _clearCanvas() {
    setState(() {
      _points.clear();
    });
  }

  void _previousPage() {
    if (_currentPage > 0) {
      setState(() {
        _currentPage--;
        _clearCanvas();
      });
    }
  }

  void _nextPage() {
    if (_currentPage < _scriptures.length - 1) {
      setState(() {
        _currentPage++;
        _clearCanvas();
      });
    }
  }
}

class ClipRounded extends StatelessWidget {
  final Widget child;
  final double radius;

  const ClipRounded({
    Key? key,
    required this.child,
    this.radius = 4.0,
  }) : super(key: key);

  @override
  Widget build(BuildContext context) {
    return ClipRRect(
      borderRadius: BorderRadius.circular(radius),
      child: child,
    );
  }
}

class DrawingPainter extends CustomPainter {
  final List<DrawingPoint?> points;

  DrawingPainter(this.points);

  @override
  void paint(Canvas canvas, Size size) {
    for (int i = 0; i < points.length - 1; i++) {
      if (points[i] != null && points[i + 1] != null) {
        canvas.drawLine(points[i]!.position, points[i + 1]!.position, points[i]!.paint);
      } else if (points[i] != null && points[i + 1] == null) {
        canvas.drawPoints(PointMode.points, [points[i]!.position], points[i]!.paint);
      }
    }
  }

  @override
  bool shouldRepaint(covariant CustomPainter oldDelegate) {
    return true;
  }
}

class GridPainter extends CustomPainter {
  @override
  void paint(Canvas canvas, Size size) {
    final paint = Paint()
      ..color = Colors.grey.withOpacity(0.2)
      ..strokeWidth = 1;

    // 横线
    for (double i = 0; i <= size.height; i += 40) {
      canvas.drawLine(Offset(0, i), Offset(size.width, i), paint);
    }

    // 竖线
    for (double i = 0; i <= size.width; i += 40) {
      canvas.drawLine(Offset(i, 0), Offset(i, size.height), paint);
    }
  }

  @override
  bool shouldRepaint(covariant CustomPainter oldDelegate) {
    return false;
  }
}

class DrawingPoint {
  final Offset position;
  final Paint paint;

  DrawingPoint(this.position, this.paint);
} 